package logic

import (
	"context"
	"errors"
	"order/internal/svc"
	"order/model"
	"order/order"

	"github.com/zeromicro/go-zero/core/logx"
)

type DeleteOrderLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewDeleteOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteOrderLogic {
	return &DeleteOrderLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *DeleteOrderLogic) DeleteOrder(in *order.DeleteOrderRequest) (*order.DeleteOrderResponse, error) {
	// todo: add your logic here and delete this line
	//result := model.Db.Delete(&model.Order{}, in.Id)
	//if result.Error != nil && result.RowsAffected <= 0 {
	//	return nil, errors.New("商品删除失败")
	//}
	//return &order.DeleteOrderResponse{
	//	Id: in.Id,
	//}, nil
	orderInfo, err := model.FindOrderById(in.Id)
	if err != nil && orderInfo.ID <= 0 {
		return nil, errors.New("订单不纯在")
	}
	if in.Id == 0 {
		return nil, errors.New("订单id不能为空")
	}

	tx := model.Db
	if result := tx.Where("id = ?", in.Id).Delete(&model.Order{}); result.Error != nil {
		tx.Callback()
		return nil, errors.New("订单删除失败")
	}
	if err := tx.Where("order_id = ?", in.Id).Delete(&model.OrderGoods{}).Error; err != nil {
		tx.Callback()
		return nil, errors.New("订单删除失败")
	}
	tx.Commit()

	return &order.DeleteOrderResponse{
		OrderData: &order.OrderData{
			Id: in.Id,
		},
	}, nil

}
